﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;

public partial class UserControl_ControlSetSKUForTDVStep2 : System.Web.UI.UserControl
{
    ClassExecute.ClassExecute dt;
    string str = webapp4U.Configuration.CurrentConnectionString;
    string error = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Request.QueryString["TDV"] != null)
            {
                //nằm trong thread
                ThreadStart thrstar = new ThreadStart(delegate() { LoadInfoTDV(Request.QueryString["TDV"].ToString()); });
                Thread tr = new Thread(thrstar);

                ThreadStart thrstar1 = new ThreadStart(delegate() { LoadSP(Request.QueryString["TDV"].ToString()); });
                Thread tr1 = new Thread(thrstar1);

                tr.Start();
                tr1.Start();

                tr.Join();
                tr1.Join();
                //nằm trong thread
               
            }
        }
        SendMail();
    }
    void LoadSP(string salesp_key)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            DataTable db = dt.Get_Data_DataTable(str, ref error, "[k_getInfoProductForSetUp]", CommandType.StoredProcedure,
                new SqlParameter("@salesp_key",salesp_key));
            if (db.Rows.Count > 0)
            {
                grvProduct.DataSource = db;
            }
            else
            {
                grvProduct.DataSource = null;
            }
            grvProduct.DataBind();
        }
        catch (Exception ex)
        {
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
    protected void imgBtnSave_Click(object sender, ImageClickEventArgs e)
    {
         dt = new ClassExecute.ClassExecute();
         try
         {
             CheckBox c;
             Label Itemkey;
             string Array = "";
            
             for (int i = 0; i < grvProduct.Rows.Count; i++)
             {
                 c = (CheckBox)grvProduct.Rows[i].FindControl("CheckApprove");
                 if (c.Checked)
                 {

                     Itemkey = (Label)grvProduct.Rows[i].FindControl("lblitemkey");
                     Array = Array + Itemkey.Text + ",";   
                 }
             }
             bool kq = dt.ExecuteSQl_bool(str, CommandType.StoredProcedure, "k_insertSalesSKU", ref error,
                         new SqlParameter("@salespkey", Request.QueryString["TDV"].ToString()),
                         new SqlParameter("@arrayItemkey", Array.Substring(0, Array.Length - 1)),
                         new SqlParameter("@RecUser", Session["user"].ToString()));
                
             //kiểm tra conflict
             DataTable getReturn = dt.Get_Data_DataTable(str, ref error, "[k_checkConflictSKU]", CommandType.StoredProcedure,
                 new SqlParameter("@SalesPKey", Request.QueryString["TDV"].ToString()));
             if (getReturn.Rows.Count > 0)
             {
                 //nếu có thì show dữ liệu
                 grvDup.DataSource = getReturn;
                 grvDup.DataBind();

                 //xóa những thông tin trùng
                 RemoveDuplicated();

                 //Load lại thông tin sản phẩm đã lưu 
                 LoadSP(Request.QueryString["TDV"].ToString());
                 //đổi tab
                 TabContainer1.ActiveTabIndex = 1;

                 ShowMessageBox("Bạn đã phân sản phẩm trùng với những trình dược viên khác,do đó những sản phẩm gắn liền với khách hàng sau đây sẽ không được lưu vào hệ thống cho : " + lblTDV.Text);


                
             }
             else
             {
                 ShowMessageBox("Bạn đã phân mặt hàng thành công cho TDV: " + lblTDV.Text);
             }
            
         }
         catch (Exception ex)
         {

             string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
             dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
         }   
    }
    protected void imgBtnBack_Click(object sender, ImageClickEventArgs e)
    {
        Response.Redirect(webapp4U.Globals.ApplicationPath + "Pages/SetSKUForTDV/Default.aspx");
    }
    protected void imgBtnDelete_Click(object sender, ImageClickEventArgs e)
    {
         dt = new ClassExecute.ClassExecute();
         try
         {
             bool kq = dt.ExecuteSQl_bool(str, CommandType.StoredProcedure, "k_deleteSalesSKU", ref error,
                         new SqlParameter("@salespkey", Request.QueryString["TDV"].ToString()));
             ShowMessageBox("Nghiệp vụ xóa thành công");
             LoadSP(Request.QueryString["TDV"].ToString());
         }
         catch (Exception ex)
         {

             string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
             dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
         }   
    }
    protected void ImgBtnNext_Click(object sender, ImageClickEventArgs e)
    {
        Response.Redirect(webapp4U.Globals.ApplicationPath + "Pages/SetRouteTDVFinal/Default.aspx?TDV=" + Request.QueryString["TDV"].ToString());
       
    }
    void LoadInfoTDV(string salesp_key)
    {
          dt = new ClassExecute.ClassExecute();
          try
          {
              lblTDV.Text = dt.GetDataDepend(str, "k_getInforTDV", CommandType.StoredProcedure, ref error,
                  new SqlParameter("@salesp_key", salesp_key));
          }
          catch (Exception ex)
          {
              string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
              dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
          }
    }
    void ShowMessageBox(string text)
    {
        MessageBox.Text = text;
        MessageBox.ShowOnPageLoad = true;
    }
    void RemoveDuplicated()
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            Label Itemkey;
            for (int i = 0; i < grvDup.Rows.Count; i++)
            {

                Itemkey = (Label)grvDup.Rows[i].FindControl("lblItemkey");


                bool kq = dt.ExecuteSQl_bool(str, CommandType.StoredProcedure, "k_deletesalesSKuDup", ref error,
                          new SqlParameter("@salesp_key", Request.QueryString["TDV"].ToString()),
                          new SqlParameter("@Itemkey", Itemkey.Text));

            }
            LoadSP(Request.QueryString["TDV"].ToString());

        }
        catch (Exception ex)
        {
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
    void SendMail()
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            DataTable db = dt.Get_Data_DataTable(str, ref error, "[k_checlForSendMailApprove]", CommandType.StoredProcedure);
              

            if (db.Rows.Count > 0)
            {

                //gửi mail
                ClassSendMail newObj = new ClassSendMail();
                newObj.Send_Email("khoi.nguyenhongmanh@gmail.com", "quynhanh.nguyentran@pierre-fabre.vn", "Fimex Sys-Approve Route", "Bạn vui lòng vào hệ thống phần mềm approve cho TDV");

            }


        }
        catch (Exception ex)
        {
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
}